package snafu.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Observable;
import java.util.Observer;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import snafu.controller.Processor;
import snafu.controller.WorldController;

public class ControlPanel extends JPanel implements Observer {
	private Processor processor;
	private JButton pauseButton, playButton, stepButton;
	private JSpinner delaySpinner;
	
	public ControlPanel(WorldController controller) {
		processor = controller.getProcessor();	
		setLayout(new GridLayout(1, 10));
		
		pauseButton = new JButton(new AbstractAction("||") {
			@Override
			public void actionPerformed(ActionEvent e) {
				pause();
			}
		});
		add(pauseButton);
		
		playButton = new JButton(new AbstractAction(">") {
			@Override
			public void actionPerformed(ActionEvent e) {
				play();
			}
		});
		add(playButton);
		
		stepButton = new JButton(new AbstractAction(">|") {
			@Override
			public void actionPerformed(ActionEvent e) {
				step();
			}
		});
		add(stepButton);
		
		SpinnerNumberModel delaySpinnerModel = new SpinnerNumberModel(50, 10, 10000, 10);
		delaySpinner = new JSpinner(delaySpinnerModel);
		delaySpinner.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				changeDelay();
			}
		});
		processor.setDelay(delaySpinnerModel.getNumber().intValue());
		add(delaySpinner);
		
		enableButtons();
	}
	
	private void pause() {
		processor.stop();
		enableButtons();
	}
	
	private void play() {
		processor.start();
		enableButtons();
	}
	
	private void step() {
		processor.step();
		enableButtons();
	}
	
	private void changeDelay() {
		SpinnerNumberModel delaySpinnerModel = (SpinnerNumberModel) delaySpinner.getModel();
		processor.setDelay(delaySpinnerModel.getNumber().intValue());
	}
	
	private void enableButtons() {
		boolean isExhausted = processor.getCurrentRound() == processor.getMaxRounds();
		boolean isRunning = processor.isRunning();
		
		pauseButton.setEnabled(!isExhausted && isRunning);
		playButton.setEnabled(!isExhausted && !isRunning);
		stepButton.setEnabled(!isExhausted && !isRunning);
		delaySpinner.setEnabled(!isExhausted && !isRunning);
	}
	
	@Override
	public void update(Observable o, Object arg) {
		enableButtons();
	}
}
